//
//  NetUtils.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/12/22.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "NetUtils.h"
#include <netdb.h>
#include <arpa/inet.h>

@implementation NetUtils

+(PHAccountType)typeWithName:(NSString *)username {
    if ([NSString dd_checkMobileNumber:username]) {
        return PHAccountTypePhone;
    } else if ([NSString dd_checkEmail:username]) {
        return PHAccountTypeEmail;
    }
    return PHAccountTypeUnknown;
}

+(AFHTTPSessionManager *)HTTPManager {
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.timeoutIntervalForRequest = 5.0f;
    NSURL *baseUrl = [NSURL URLWithString:kBaseURL];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl sessionConfiguration:config];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    if (APP_DELEGATE.token) {
        [manager.requestSerializer setValue:APP_DELEGATE.token.token forHTTPHeaderField:@"x-token"];
    }
    return manager;
}

+(AFHTTPSessionManager *)JSONManager {
    AFHTTPSessionManager *manager = [NetUtils HTTPManager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    if (APP_DELEGATE.token) {
        [manager.requestSerializer setValue:APP_DELEGATE.token.token forHTTPHeaderField:@"x-token"];
    }
//    LOG(@"header %@",manager.requestSerializer.HTTPRequestHeaders);
    return manager;
}

+(void)loginWithType:(PHAccountType)type name:(NSString *)name password:(NSString *)password finish:(FinishBlock)finish {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[NSString stringWithFormat:@"%ld", (unsigned long)type] forKey:@"type"];
    [parameters setObject:name forKey:@"user_name"];
    if (password) {
        [parameters setObject:[password qmui_md5] forKey:@"password"];
    }
    LOG(@"parameters %@",parameters);
    
    [KKHUD showLoading:NSLocalizedString(@"tips_signining", nil)];
    [[NetUtils JSONManager] POST:@"user/login.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        if (result && result.is_result_suc) {
            
            NSString *user_id = result.object_result[@"user_id"];
            NSString *token = result.object_result[@"x-token"];
            
            APP_DELEGATE.token = [PHToken tokenWithName:name userId:user_id token:token];
            [GGlobalUser getUserInfo:YES finish:^(BOOL success) {
                APP_DELEGATE.loginSuccess = success;
            }];
            
            !finish ?: finish(YES);
        } else {
            [KKHUD showError:result.error_msg];
            !finish ?: finish(NO);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
        !finish ?: finish(NO);
    }];
}

+(void)registerWithType:(PHAccountType)type name:(NSString *)name code:(NSString *)code third_id:(NSString *)third_id password:(NSString *)password {
    NSMutableDictionary *user = [NSMutableDictionary dictionary];
    [user setObject:[NSString stringWithFormat:@"%ld", (unsigned long)type] forKey:@"type"];
    if ([NSString dd_checkMobileNumber:name]) {
        [user setObject:name forKey:@"phone"];
    } else if ([NSString dd_checkEmail:name]) {
        [user setObject:name forKey:@"email"];
    }
    if (third_id) {
        [user setObject:third_id forKey:@"third_id"];
    }
    
    if (code) {
        [user setObject:code forKey:@"code"];
    }
    
    if (password) {
        [user setObject:password forKey:@"password"];
    }
    
    NSDictionary *parameters = @{ @"user": user };
    LOG(@"parameters %@",parameters);
    
    [KKHUD showLoading:NSLocalizedString(@"tips_registering", nil)];
    [[NetUtils JSONManager] POST:@"user/createUser.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        
        if (result.is_result_suc) {
            if (type == PHAccountTypeWechat) {
                [NetUtils loginWithType:type name:third_id password:nil finish:nil];
            } else {
                [NetUtils loginWithType:type name:name password:password finish:nil];
            }
        } else {
            [KKHUD showError:result.error_msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

+(void)findPasswordWithType:(PHAccountType)type name:(NSString *)name code:(NSString *)code password:(NSString *)password {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (type == PHAccountTypePhone) {
        [parameters setObject:name forKey:@"phone"];
    } else if (type == PHAccountTypeEmail) {
        [parameters setObject:name forKey:@"email"];
    }
    
    [parameters setObject:code forKey:@"code"];
    
    if (password.length > 0) {
        [parameters setObject:[password dd_md5] forKey:@"new_password"];
    }
    
    LOG(@"parameters %@",parameters);
    [KKHUD showLoading:NSLocalizedString(@"btn_reset_password", nil)];
    [[NetUtils JSONManager] POST:@"user/findPassword.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        
        if (result.is_result_suc) {
            [NetUtils loginWithType:type name:name password:password finish:nil];
        } else {
            [KKHUD showError:result.error_msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

+(void)checkThirdType:(PHAccountType)type third_id:(NSString *)third_id finish:(FinishBlock)finish {
    
    NSDictionary *parameters = @{ @"type": [NSString stringWithFormat:@"%d", (int)type], @"third_id": third_id };
    LOG(@"parameters %@", parameters);
    
    [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    [[NetUtils JSONManager] POST:@"user/checkThirdId.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        
        if (result.is_result_suc) {
            [KKHUD hide];
            !finish ?: finish(YES);
        } else {
            [KKHUD showError:result.error_msg];
            !finish ?: finish(NO);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
        !finish ?: finish(NO);
    }];
}

@end
